import datetime
import pytz

import warningExtractor
import common

def loadStormReports(years, source = 'NCDC'):
	if source == 'NCDC':
		return loadNCDCStormReports(years)
	elif source == 'SPC':
		return loadSPCStormReports(years)

def loadNCDCStormReports(years):
	countyList = warningExtractor.loadCountyList()
	
	reports = []
	utc = pytz.utc
	central = pytz.timezone("US/Central")
	
	for year in years:
		fPath = ''
		if year >= 2000 and year <= 2007:
			fPath = '%s/ncdc/tor-2000-2007.csv'%common.StormReportDir
		elif year >= 2008 and year <= 2012:
			fPath = '%s/ncdc/tor-2008-2012.csv'%common.StormReportDir
		
		f = open(fPath, 'r')
		for line in f:
			lineParts = line.split(',')
			if len(lineParts) != 35:
				continue
			
			dateParts = lineParts[3].split('/')
			timeStr = lineParts[4].zfill(4)
			
			if int(dateParts[2]) != year:
				continue
			
			dt1 = datetime.datetime(int(dateParts[2]),
									int(dateParts[0]),
									int(dateParts[1]),
									int(timeStr[0:2]),
									int(timeStr[2:4]),
									0)
			
			# all the reports are UTC-6
			utcStormTime = dt1 + datetime.timedelta(hours = 6)
			utcStormTime = utc.localize(utcStormTime)
			#stormTime = central.localize(dt1)
			#utcStormTime = stormTime.astimezone(utc)

			slat = -1
			slon = -1
			elat = -1
			elon = -1
			
			if len(lineParts[30].strip()) > 0:
				slat = float(lineParts[30])
			if len(lineParts[31].strip()) > 0:
				slon = float(lineParts[31])
			if len(lineParts[32].strip()) > 0:
				elat = float(lineParts[32])
			if len(lineParts[33].strip()) > 0:
				elon = float(lineParts[33])

			ef = -1
			if len(lineParts[7].strip()) == 3:
				ef = int(lineParts[7][2:])
			
			inj = -1
			if len(lineParts[19].strip()) > 0:
				inj = int(lineParts[19])
			
			fat = -1
			if len(lineParts[8].strip()) > 0:
				fat = int(lineParts[8])
				
			length = -1
			width = -1
			fips1 = -1
			
			if len(lineParts[23].strip()) > 0:
				length = float(lineParts[23])
			if len(lineParts[24].strip()) > 0:
				width = float(lineParts[24])
			if len(lineParts[17].strip()) > 0:
				fips1 = float(lineParts[17])

			report = {"time":utcStormTime,						# estimated touchdown time
						"state":lineParts[12],
						"ef":ef,           						# tornado ef rating
						"inj":inj,								# injuries
						"fat":fat,								# fatalities
						"slat":slat,          					# starting latitude
						"slon":slon,          	
						"elat":elat,				          	# endng latitude
						"elon":elon,
						"length":length,        				# path length
						"width":width, 				          	# path width
						"fips1":fips1,			  				# official 1st county code
						"fips2":-1,
						"fips3":-1,
						"fips4":-1}

			# limit to OK tornadoes
			
			visCounty = False
			for code in countyList.keys():
				if code == report['fips1']:
					visCounty = True
			
			if visCounty and lineParts[18] == 'OUN':
				reports.append(report)
	f.close()
	return reports


def loadSPCStormReports(years):
	countyList = warningExtractor.loadCountyList()
	
	reports = []
	utc = pytz.utc
	central = pytz.timezone("US/Central")
	for year in years:
		fPath = ''
		if year >= 2000 and year <= 2004:
			fPath = '%s/spc/tor-2000-2004.csv'%common.StormReportDir
		elif year >= 2005 and year <= 2007:
			fPath = '%s/spc/tor-2005-2007.csv'%common.StormReportDir
		else:
			fPath = "%s/spc/tor-%d.csv"%(common.StormReportDir, year)
		
		f = open(fPath, 'r')
		for line in f:
			lineParts = line.split(',')
			if len(lineParts) != 28:
				continue
			timeParts = lineParts[5].split(':')
			
			if int(lineParts[1]) != year:
				continue
			
			dt1 = datetime.datetime(int(lineParts[1]),
									int(lineParts[2]),
									int(lineParts[3]),
									int(timeParts[0]),
									int(timeParts[1]),
									int(timeParts[2]))
			
			stormTime = central.localize(dt1)
			utcStormTime = stormTime.astimezone(utc)

			report = {"time":utcStormTime,						# estimated touchdown time
						"state":lineParts[7],
						"ef":int(lineParts[10]),              	# tornado ef rating
						"inj":int(lineParts[11]),				# injuries
						"fat":int(lineParts[12]),				# fatalities
						"slat":float(lineParts[15]),          	# starting latitude
						"slon":float(lineParts[16]),          
						"elat":float(lineParts[17]),          	# endng latitude
						"elon":float(lineParts[18]),
						"length":float(lineParts[19]),        	# path length
						"width":int(lineParts[20]),           	# path width
						"fips1":int(lineParts[24]),			  	# official 1st county code
						"fips2":int(lineParts[25]),				# 2nd county code (if tornado moves through multiple counties)
						"fips3":int(lineParts[26]),
						"fips4":int(lineParts[27])}

			# limit to OK tornadoes
			if report['state'] == 'OK':
				visCounty = False
				for code in countyList.keys():
					if code in [report['fips1'], report['fips2'], report['fips3'], report['fips4']]:
						visCounty = True
				
				if visCounty:
					reports.append(report)
	f.close()
	return reports
	

